var app = getApp();
var util = app.util;
var maiList = app.http.anchor_mailistPost; //接口 排麦列表
var get_dakadata = app.http.get_dakadataPost; //接口 大光福利.冠厅等等列表  
var save_benefit = app.http.save_benefitsPost; //接口 打卡保存
var upload_img = app.http.config.upload_img //接口 上传图片
var base_punish = app.http.base_punishPost //接口 修改魅力值1 修改本档任务2  修改惩罚措施3  修改补档工资
var updateStatus = app.http.updateStatusPost //接口 更新状态
var cftype = app.http.check_cf_typePost //判断惩罚方式
var savedakainfo = app.http.save_dakainfoPost //接口提交打卡信息
var check_role = app.http.check_rolePost //接口检查角色  role 1主持  2主播  3既不是主播也不是主持

Component({
    properties: {
        
    },
    data: {
        jurisdiction: false // false 只能看 不能操作
            ,
        is_onshow: true //true 调onshow 方法 false不调
            ,
        get_dakadata: [] //大光福利.冠厅等等列表
            ,
        dagunagButton: [{
                text: '取消'
            }, {
                text: '确定',
                extClass: 'daguangSure'
            }] //大光福利弹出框 按钮
            ,
        dialogDaguangShow: false //大光福利 弹出框  true显示 
            ,
        isedit: 1 // 打卡 0是新增   1 是修改 默认
            ,
        kong_num: 0 //未排的数量
            ,
        roles: 3 // 1主持人 2主播  3既不是主播也不是主持
            ,
        dakaMailistArr: [],
        dakadatalistArr: [],
        update_status: 0 //1是补卡
            ,
        zhuchidaka_isshow: 0 //0 不显示 1显示
            ,
        typeAndshouyiren: true //true 是大光和福利和惩罚  的类型和用户人都填写  false 则非        
    },
    attached: function () {

        //调接口
        // this.shwjiekou();

    },
    ready: function () {},
    methods: {
        //初始化接口数据
        showjiekou(){
            var that = this
            wx.getSystemInfo({
                success: function (res) {
                    var itemHeight = res.windowHeight;
                    //底部高度 rpx
                    var safeAreaBottom = (res.screenHeight - res.safeArea.bottom) * (750 / res.windowWidth)
                    that.setData({
                        windowHeight: itemHeight,
                        safeAreaBottom
                    });
                }
            })
            //档期
            var dangqiInfo = wx.getStorageSync('dangqiInfo')
            var beteenTime = dangqiInfo.starttime + " — " + dangqiInfo.endtime
            var daka_time = wx.getStorageSync('hall_info').daka_time //打卡时间
            this.setData({
                dangqiInfo,
                daka_time
            })
            //是否已超过打卡时间
            this.setData({
                outtime: this.outtime()
            })
            //补卡
            if (wx.getStorageSync("update_status")) {
                this.setData({
                    update_status: 1
                })
            }
            if (this.data.is_onshow) {
              //排麦表
              this.getmaiList(true);
              //角色接口
              this.check_roleJk(function (err, res) {
                  if (!err) {
                      let roles = res.role
                      //打卡时间已过 档期内是主播 外是小程序管理员 则改成 是小程序管理员
                      if (that.outtime() && roles == 2 && wx.getStorageSync("userinfo").roles.indexOf("1") != -1) {
                          roles = 3
                      }
                      that.setData({
                          roles: roles
                      })

                      //接口大光福利.冠厅等等列表
                      that.getdakadata(false, roles);
                      //删除按钮 添加按钮 显示
                      that.showdelet()
                      //打卡确定按钮 显示
                      that.dakasure()
                      //排麦主持是否显示
                      that.zhuchishow()
                  } else {
                      console.log("获取角色接口报错")
                  }
              });
            }

        },
        /*
         *  上传图片
         */
        chooseImage: function (e) {
            let bottomindex = e.currentTarget.dataset.index;
            let userindex = e.currentTarget.dataset.userindex;
            //判断是否有操作权限
            if (this.quanxianfuli(this.data.get_dakadata[bottomindex]) == 0) {
                return;
            }
            //获取pic

            var pics = this.data.get_dakadata[bottomindex].userlist[userindex].pics ? this.data.get_dakadata[bottomindex].userlist[userindex].pics : ''

            var self = this
            //chooseImage 会调用onshow 设置 接口不调用
            self.setData({
                bottomindex,
                userindex,
                is_onshow: false
            })

            wx.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album'],
                success: function (res) {
                    //console.log('chooseImage success, temp path is', res.tempFilePaths[0])

                    var imageSrc = res.tempFilePaths[0]
                    wx.showLoading({
                        title: '加载中...',
                        mask: true
                    })
                    wx.uploadFile({
                        url: upload_img,
                        filePath: imageSrc,
                        name: 'img',
                        formData: {
                            "token": wx.getStorageSync('userinfo').token
                        },
                        success: function (res) {
                            if (res.statusCode == 200) {
                                //设置pics
                                var imgurl = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].pics'
                                if (pics) {
                                    pics += "," + JSON.parse(res.data).url
                                } else {
                                    pics += JSON.parse(res.data).url
                                }
                                self.setData({
                                    [imgurl]: pics
                                })
                                //保存
                                self.addUserdaka();
                            } else {
                                console.log('上传图片失败', res)
                            }
                            wx.hideLoading()
                        },
                        fail: function ({
                            errMsg
                        }) {
                            console.log('上传图片fail', errMsg)
                            wx.hideLoading()
                        }
                    })

                },
                fail: function ({
                    errMsg
                }) {
                    console.log('选择图片chooseImage fail, err is', errMsg)
                }
            })
        },
        //删除打卡图片
        delImage: function (e) {
            let bottomindex = e.currentTarget.dataset.index;
            let userindex = e.currentTarget.dataset.userindex;
            //判断是否有操作权限
            if (this.quanxianfuli(this.data.get_dakadata[bottomindex]) == 0) {
                return;
            }
            //获取pic
            let imgindex = e.currentTarget.dataset.imgindex;
            //删除数组图片
            var pics_arr = this.data.get_dakadata[bottomindex].userlist[userindex].pics.split(",")
            pics_arr.splice(imgindex, 1);
            var imgurl = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].pics'
            //chooseImage 会调用onshow 设置 接口不调用
            this.setData({
                bottomindex,
                userindex,
                [imgurl]: pics_arr.join(",")
            })
            //保存
            this.addUserdaka();
        },

  //大光福利.冠厅等等列表 roles 1 是主持 2主播
  getdakadata(loading = true, roles = 1) {
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    var token = wx.getStorageSync('userinfo').token
    var hall_id = wx.getStorageSync('hall_info').id
    var data_type = roles  //角色
    //补卡
    if (wx.getStorageSync("update_status")){
      data_type = 1  
    }
    get_dakadata({
      token,
      did: dangqiInfo.id,
      hall_id,
      datatype: data_type
    }, loading).then(re => {
      if (re.code == 0) {
        let get_dakadata = re.data

        this.setData({
          get_dakadata: get_dakadata
        })

      } else {
        console.log("获取打卡信息接口返回数据失败");
      }
    })
  },
  //底部弹出框
  selectTitle(e) {
    let userindex = e.currentTarget.dataset.userindex;
    let bottomindex = e.currentTarget.dataset.index;
    let dakadata_info = this.data.get_dakadata[bottomindex]
    //判断是否有操作权限
    if (this.quanxianfuli(dakadata_info) == 0) {
      return;
    }

     
    let benefitlist = dakadata_info.benefitlist
    var isedit = 0;

    this.setData({
      isedit,
      bottomDialogTitle: dakadata_info.name,
      bottomDialogArray: benefitlist,
      bottomindex: bottomindex,
      userindex: userindex   //默认空
    })

    if (dakadata_info.type == 2) {
      //大光福利 弹出框
      this.triggerEvent("daguangDialog", {dialogDaguangShow:true});

    //   this.setData({
    //     dialogDaguangShow: true
    //   })

    } else {
      if (Number(dakadata_info.type) == 4){
        //页面传递
        this.triggerEvent("shouyiren", {bottomindex:bottomindex,userindex:userindex,get_dakadata:this.data.get_dakadata,isedit:isedit,tid:0});
        wx.navigateTo({
          url: "../main_shouyiren/main_shouyiren"
        })
      }else{
        //显示弹框  传到复页面
        this.triggerEvent("bottomDialog", {bottomDialogArray:benefitlist,bottomDialogTitle:dakadata_info.name,bottomindex});

        // var bottomDialog = this.selectComponent("#bottomDialog")
        // bottomDialog.setData({
        //   hideFlag: false
        // })
        // bottomDialog.showModal();
      }
    }

  },
  //修改打卡子标题
  gengxinselectTitle(e) {
    let bottomindex = e.currentTarget.dataset.index;
    var userindex = e.currentTarget.dataset.userindex;
    var dakadata_info = this.data.get_dakadata[bottomindex]
    var benefitlist = dakadata_info.benefitlist
    //判断是否有操作权限
    if (this.quanxianfuli(dakadata_info) == 0){
       return;
    }
      
      //如果type == 4 是惩罚 将 title 值复制到 name
      // if (Number(dakadata_info.type) == 4){
      //   benefitlist.forEach((item,index)=>{
      //     benefitlist[index]["name"] = item.title;
      //   })
      // }

      this.setData({
        userindex,
        bottomDialogTitle: dakadata_info.name,
        bottomDialogArray: benefitlist,
        bottomindex: bottomindex
      })

      if (dakadata_info.type == 2) {
        //大光福利 弹出框
        // this.setData({
        //   dialogDaguangShow: true
        // })
        this.triggerEvent("daguangDialog", {dialogDaguangShow:true});
      } else {
        //显示弹框
        this.triggerEvent("bottomDialog", {bottomDialogArray:benefitlist,bottomDialogTitle:dakadata_info.name,bottomindex});
        // var bottomDialog = this.selectComponent("#bottomDialog")
        // bottomDialog.setData({
        //   hideFlag: false
        // })
        // bottomDialog.showModal();
      }
    
  },
  //底部弹出框 回调方法
  bottomDialogIndex(e) {
    var that = this
    var index = e.detail.index;
    var type = e.detail.type;
    console.log(e,"底部弹出框");
    //打卡排麦 底部修改
    if (type == "dakapaimai") {
      var name = this.data.baseselectArray[index].name + ""
      var base_paimaiUid = this.data.base_paimaiUid
      this.chengfashange(name, base_paimaiUid, type,function(err,res){
        if (err==null){
              if (!res){
                wx.showToast({
                  title: '请选择其他的惩罚方式',
                  icon: 'none'
                })
              }else{
                that.base_punish(index);
              }
        }  
       
      });

    } else {
      //打卡 修改
      var bottomindex = this.data.bottomindex
      var bottomName = this.data.get_dakadata[bottomindex].benefitlist[index].name
      var bottom_id = this.data.get_dakadata[bottomindex].benefitlist[index].id
      var tid = this.data.get_dakadata[bottomindex].benefitlist[index].id   //底部弹框 选项的id
      var userindex = this.data.userindex
      var j = 0;  
    //   if (userindex >= 0 ) {
    //     //判断类型重复
    //     if (this.data.get_dakadata[bottomindex].userlist[userindex] && this.data.get_dakadata[bottomindex].userlist[userindex].nickname) {
    //       var userlist = this.data.get_dakadata[bottomindex].userlist  //userlist
    //       var fuliname = userlist[userindex].nickname                  //受益人
    //       for (var i = 0; i < userlist.length; i++) {
    //         //isedit 是已经删除的福利
    //         if (userlist[i].isedit && userlist[i].isedit == 2){
    //           continue 
    //         }
    //         if (userlist[i].nickname == fuliname) {
    //           if (bottom_id == Number(userlist[i]["tid"])) {
    //             j = 1;
    //             break;
    //           }
    //         }
    //       }
    //     }
    //   }

      if (j) {
        wx.showToast({
          title: '重新选择,同类型的受益人已存在',
          icon: 'none'
        })

      } else {
        
        //用户uid
        var cf_uid = 0;
        if (this.data.get_dakadata[bottomindex]["userlist"][userindex] && this.data.get_dakadata[bottomindex]["userlist"][userindex]["nickname"]){
          let userdata = this.data.get_dakadata[bottomindex]["userlist"][userindex]
           cf_uid = userdata.userUid ? userdata.userUid : userdata.touid
        }

        //如果是主播并且不是惩罚则添加用户uid 和 nickname
        if (Number(that.data.get_dakadata[bottomindex].type) != 4 && this.data.roles == 2 && !this.outtime()){
          cf_uid = wx.getStorageSync('userinfo').uid
          let nickname = wx.getStorageSync('userinfo').nickname
          let cfuid_tr = "get_dakadata["+bottomindex+"].userlist["+userindex+"].userUid" 
          let nickname_tr = "get_dakadata[" + bottomindex + "].userlist[" + userindex +"].nickname" 
          that.setData({
            [cfuid_tr]: cf_uid,
            [nickname_tr]: nickname
          })
        }
       

        var name = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].name';
        console.log(name, bottomName, "65655555")
        that.setData({
          [name]: bottomName,
          tid,
          bottomName,
          benefitIndex: index
        })
        // 更新或保存
        that.addUserdaka();

        //判断 周工资全减、日工资全减 周工资 是否可选
        // var bottomTitle = this.data.get_dakadata[bottomindex].benefitlist[index].title? this.data.get_dakadata[bottomindex].benefitlist[index].title : this.data.get_dakadata[bottomindex].benefitlist[index].name
        // let cftype = ""
        // if (this.data.get_dakadata[bottomindex].type == 4){
        //   cftype = this.data.get_dakadata[bottomindex].benefitlist[index].title
        // }
        // this.chengfashange(cftype, cf_uid, "fuli", function (err, res){
        //   if (err == null) {
        //     if (res == 0) {
        //       wx.showToast({
        //         title: '请选择其他的惩罚方式',
        //         icon: 'none'
        //       })
        //     } else {
        //       var name =  'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].name';
        //       var title = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].title'
        //       console.log(name, bottomName,"65655555")
        //       that.setData({
        //         [name]: bottomName,
        //         [title]: cftype,
        //         tid,
        //         bottomName,
        //         benefitIndex: index
        //       })
        //       // 更新或保存
        //       that.addUserdaka();
        //     }
        //   } 
        // });
      }
    }
  },
  //接口 添加 全麦福利/惩罚 等等
  addUserdaka() {
  
    var that = this
    var index = this.data.bottomindex  //某一项的下标  例如 大光福利 冠厅 办卡
    var benefitIndex = this.data.benefitIndex  //某一项的子项的下标  
    var userindex = this.data.userindex  //某一项的子项的下标   
    //小id
    var tid = this.data.tid;
    var othertid = this.data.tid;
    var punish_id = this.data.tid;
    this.setData({
      ['get_dakadata[' + index + '].userlist[' + userindex + '].tid']: tid,
      ['get_dakadata[' + index + '].userlist[' + userindex + '].othertid']: othertid,
      ['get_dakadata[' + index + '].userlist[' + userindex + '].punish_id']: punish_id
    }) 
    //保存提交的接口数据
    this.dakadatalistArr()
  },
  //大光福利 弹出框 输入的数字
  daguangNumber(e) {
    if (e.detail.value) {
      this.setData({
        daguangnum: e.detail.value
      })
    }

  },
  //大光福利 弹出框  按钮回调事件
  daguangSure(e) {
    //确定按钮
    if (e.detail.index == 1) {
      var daguangnum = this.data.daguangnum
      var bottomindex = this.data.bottomindex
      var userindex = this.data.userindex
      var j = 0

    //   if (this.data.userindex >= 0 && typeof this.data.userindex === 'number') {
    //     //判断类型重复
    //     if (this.data.get_dakadata[bottomindex].userlist[userindex] && this.data.get_dakadata[bottomindex].userlist[userindex].nickname) {
    //       var userlist = this.data.get_dakadata[bottomindex].userlist
    //       var fuliname = userlist[userindex].nickname
    //       for (var i = 0; i < userlist.length; i++) {
    //         if (userlist[i].nickname == fuliname) {
    //           if (daguangnum == userlist[i]["daguangnum"]) {
    //             j = 1;
    //             break;
    //           }
    //         }
    //       }
    //     }
    //   }
      if (this.data.daguangnum) {

        //判断输入的数字是否在范围内
        let isdaguang_bef = 0;
        var benefitlist = this.data.get_dakadata[bottomindex].benefitlist;
        console.log(benefitlist)
        for(var item of benefitlist) {
             if(daguangnum >=item.region_low && daguangnum <= item.region_high){
              isdaguang_bef = 1;
             }
        }

        if(j){
          wx.showToast({
            title: '重新输入,大光福利和受益人已存在',
            icon: 'none'
          })
        } else if (daguangnum > 99999){
          wx.showToast({
            title: '不能超过五位数字',
            icon: 'none'
          })
        }else if(!isdaguang_bef){
          wx.showToast({
            title: '您输入的大光福利不在区间内',
            icon: 'none'
          })
        }else{

          var num = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].daguangnum'
          var uid = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].userUid'
          var nickname = 'get_dakadata[' + bottomindex + '].userlist[' + userindex + '].nickname'
          //主播在打卡时间内 添加受益人自己
          if (this.data.roles == 2 && !this.outtime()){
           this.setData({
             [num]: daguangnum,
             [uid]: wx.getStorageSync("userinfo").uid,
             [nickname]: wx.getStorageSync("userinfo").nickname
           })
         }else{

           this.setData({
             [num]: daguangnum
           })
         }

          //新增和修改
          this.addUserdaka();
        //更新 
        //this.getdakadata();
        } 

      }
    }
    //取消按钮
    if (e.detail.index == 0) {

    }
    //关闭弹出框
    // this.setData({
    //   dialogDaguangShow: false,
    //   daguangnum: ''     // 数字设置空
    // })
    this.triggerEvent("daguangDialog", {dialogDaguangShow:false,daguangnum:''});
  },
  // 选择受益人
  shouyiren(e) {
    let bottomindex = e.currentTarget.dataset.index;
    //判断是否有操作权限
    if (this.quanxianfuli(this.data.get_dakadata[bottomindex]) == 0) {
      return;
    }
    let userindex = e.currentTarget.dataset.userindex;
    var isedit = 1;//修改
    var tid = this.data.get_dakadata[bottomindex].userlist[userindex].tid
    if (this.data.get_dakadata[bottomindex].type == 3) {
      if (this.data.get_dakadata[bottomindex].userlist[userindex].othertid) {
        tid = this.data.get_dakadata[bottomindex].userlist[userindex].othertid
      }
    }
    if (this.data.get_dakadata[bottomindex].type == 4) {
      if (this.data.get_dakadata[bottomindex].userlist[userindex].punish_id >= 0) {
        tid = this.data.get_dakadata[bottomindex].userlist[userindex].punish_id
      }
    }
    this.setData({
      bottomindex,
      userindex,
      tid,
      isedit
    })
    //页面传递
    this.triggerEvent("shouyiren", {bottomindex:bottomindex,userindex:userindex,get_dakadata:this.data.get_dakadata,isedit:isedit,tid:tid});
    wx.navigateTo({
      url: "../main_shouyiren/main_shouyiren"
    })
  },
  // 添加一条打卡子项
  addonedaka(e) {
      var index = e.currentTarget.dataset.index;
      //js 添加一条假信息
      var get_dakadata = this.data.get_dakadata
      // 判断是否有操作权限
      if (this.quanxianfuli(get_dakadata[index]) == 0) {
        return;
      }
      
      //判断如果是大光 全麦 并且是 主播 时只能添加一个
      // if (!this.data.update_status && this.data.roles == 2 && (get_dakadata[index].type == 2 || get_dakadata[index].type == 1)){
      //    wx.showToast({
      //      title: '同受益人只能添加一条',
      //      icon: 'none'
      //    })
      //    return;
      // }

      var insert = new Object()
      var tid = ''   //
      //主播在打卡时间内添加受益人
     if (this.data.roles == 2 && !this.outtime()){
        insert.uid = wx.getStorageSync("userinfo").uid
        insert.nickname = wx.getStorageSync("userinfo").nickname
      }
     
     //黑麦惩罚
      if (get_dakadata[index].type == 4){
        tid = get_dakadata[index].benefitlist.id
        insert.tid = tid
        insert.othertid = tid
        insert.punish_id = tid
        insert.name = get_dakadata[index].benefitlist.name
      }
      get_dakadata[index].userlist.push(insert);
      this.setData({
        get_dakadata,
        bottomindex: index,
        tid: tid,
        isedit: 0
      })
    
  },
  //删除一条打卡信息
  delonedaka(e){

    var userIndex = e.currentTarget.dataset.userindex;
    var index = e.currentTarget.dataset.index;
    //js 添加一条假信息
    var get_dakadata = this.data.get_dakadata
    // 判断是否有操作权限
    if (this.quanxianfuli(get_dakadata[index]) == 0) {
      return;
    }
    
    //删除
    if (get_dakadata[index].userlist[userIndex].id){
      //统计 删除的 个数
      let ulength = 1
      if (get_dakadata[index].userlistlength){
        ulength = get_dakadata[index].userlistlength + 1
      }
      let isedit = "get_dakadata[" + index + "].userlist[" + userIndex + "].isedit"
      let userlistlength = "get_dakadata[" + index + "].userlistlength"
      this.setData({
        [isedit]: 2,
        [userlistlength]: ulength
      })
    }else{
      get_dakadata[index].userlist.splice(userIndex, 1);
      let userlist = "get_dakadata[" + index + "].userlist"
      this.setData({
        [userlist]: get_dakadata[index].userlist
      })
    }
  
    //保存和添加数据
    this.dakadatalistArr()
  },
  //主持本档任务修改
  zhuchiupdateDaycharm(e){
    var baseselectArray = [{ name: "已完成", value: 1, type: "dakapaimai" }, { name: "未完成", value: 0, type: "dakapaimai" }]
    var title = "本档任务"

    this.setData({
      baseType: 0,
      baseselectArray: baseselectArray
    })
    //底部弹出框
    //显示弹框
    // var bottomDialog = this.selectComponent("#bottomDialog")
    // bottomDialog.setData({
    //   modelType: "select",
    //   title: title,
    //   selectArray: baseselectArray,
    //   hideFlag: false
    // })
    // bottomDialog.showModal();
    this.triggerEvent("bottomDialog", {bottomDialogArray:baseselectArray,bottomDialogTitle:title});
  },
  
  //修改魅力值1 修改本档任务2  修改惩罚措施3  修改补档工资4 惩罚措施5 弹出框
  updateDaycharm(e) {
    //不是补卡时 判断权限
    if (!wx.getStorageSync("update_status")) {
        //不是主持  
        if(this.data.roles != 1){
          wx.showToast({
            title: '没有操作权限',
            icon: 'none',
            duration: 2000
          })
          return ;
        }
        

        //超过打卡时间
        var daka_time = this.data.daka_time
        var dangqiInfo = wx.getStorageSync('dangqiInfo')
        var endtime = dangqiInfo.riqi + " " + dangqiInfo.endtime
        if (new Date().getTime() > (util.riqiTime(endtime) + Number(daka_time) * 60 * 1000)) {
          wx.showToast({
            title: '已经超过打卡时间，不能打卡',
            icon: 'none',
            duration: 2000
          })
          return;
        }
      //直播未开始
      var starttime = dangqiInfo.riqi + " " + dangqiInfo.starttime
      if (new Date().getTime() < (util.riqiTime(starttime))){
        wx.showToast({
          title: '直播未开始',
          icon: 'none',
          duration: 2000
        })
        return;
      }

    }
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    var paimaiId = this.data.maiList[index].id
    var paimaiUid = this.data.maiList[index].uid
    if (type == 1) {
      
      var baseselectArray = [{ name: "已达标", value: 1, type: "dakapaimai" }, { name: "未达标", value: 0, type: "dakapaimai" }]
      var title = "今日魅力值"
      if (this.data.maiList[index].rimeiliUp){
         wx.showToast({
           title: '不能修改',
           icon:'none'
         })
         return;
      } 

    //   if (this.data.maiList[index].rimeili){
    //     wx.showToast({
    //       title: '日魅力不能修改',
    //       icon:'none'
    //     })
    //     return;
    //  } 


    } else if (type == 2) {

      var baseselectArray = [{ name: "已完成", value: 1, type: "dakapaimai" }, { name: "未完成", value: 0, type: "dakapaimai" }]
      var title = "本档任务"

    } else if (type == 3) {

      var tiaodang_list = this.data.tiaodang_list;
      for (var i = 0; i < tiaodang_list.length; i++) {
        tiaodang_list[i].type = "dakapaimai";
      }

      var baseselectArray = tiaodang_list
      var title = "跳档惩罚"

    } else if (type == 4) {

      var title = "补档工资"
      var baseselectArray = [{ name: "有", value: 1, type: "dakapaimai" }, { name: "无", value: 0, type: "dakapaimai" }]

    } else if (type == 5) {

      var title = "惩罚措施"
      var renwucf_list = this.data.renwucf_list;
      for (var i = 0; i < renwucf_list.length; i++) {
        renwucf_list[i].type = "dakapaimai";
      }
      var baseselectArray = renwucf_list
    }
    this.setData({
      baseType: type,
      base_index: index,
      base_paimaiid: paimaiId,
      base_paimaiUid: paimaiUid,
      baseselectArray: baseselectArray
    })
    //底部弹出框
    //显示弹框
    // var bottomDialog = this.selectComponent("#bottomDialog")
    // bottomDialog.setData({
    //   modelType: "select",
    //   title: title,
    //   selectArray: baseselectArray,
    //   hideFlag: false
    // })
    // bottomDialog.showModal();
    this.triggerEvent("bottomDialog", {bottomDialogArray:baseselectArray,bottomDialogTitle:title});
  },
  //修改魅力值1 修改本档任务2  修改跳档惩罚措施3  修改补档工资4 惩罚措施5  接口
  base_punish(index) {
    
    var baseType = this.data.baseType
    var base_index = this.data.base_index
    var baseselectArray = this.data.baseselectArray
    var maiList = this.data.maiList
    //主持人自己的本档任务
    if (baseType == 0){
       this.setData({
         'zhuchi_info.task_over': baseselectArray[index].value
       })
       return;
    }
    //接口参数
    var token = wx.getStorageSync('userinfo').token
    var did = wx.getStorageSync('dangqiInfo').id
    var sid = this.data.base_paimaiid
    var daycharm = maiList[base_index].rimeili; //日魅力是否达标 0-未达标 1-已达标
    var taskend = maiList[base_index].taskend;  //本当任务完成情况0-未完成 1-已完成
    var addin_salary = maiList[base_index].addin_salary; //补档是否有工资 0-无，1-有
    //跳档惩罚 参数
    var touid = maiList[base_index].uid;  //有惩罚需要，惩罚人
    var punish_id = maiList[base_index].tripstop_punish; //惩罚id
    var type = 0
    // 惩罚措施 参数
 
    //修改
    if (baseType == 1) { //日魅力
      daycharm = baseselectArray[index].value

      var daycharm_data = 'maiList[' + base_index + '].rimeili'
      this.setData({
        [daycharm_data]: daycharm,
      })

    }
    if (baseType == 2) { //本当任务
      taskend = baseselectArray[index].value
      var daycharm_data = 'maiList[' + base_index + '].taskend'
      //本档任务已完成 设置惩罚为空
      var rwcf_id_data = 'maiList[' + base_index + '].rwcf_id'
      var rwcf_type_data = 'maiList[' + base_index + '].rwcf_type'
      if (taskend){
        this.setData({
          [daycharm_data]: taskend,
          [rwcf_id_data]: '',
          [rwcf_type_data]: ''
        })
      }else{
        this.setData({
          [daycharm_data]: taskend,
        })
      }   
    }
    if (baseType == 3) { //跳档惩罚
      type = 1
      punish_id = baseselectArray[index].id
      //修改
      var tiaodang_punish_name = baseselectArray[index].name
      var tdcf_id_data = 'maiList[' + base_index + '].tdcf_id'
      var tdcf_type_data = 'maiList[' + base_index + '].tdcf_type'
      this.setData({
        [tdcf_id_data]: punish_id,
        [tdcf_type_data]: tiaodang_punish_name,
      })
    }
    if (baseType == 4) { //补档工资
      addin_salary = baseselectArray[index].value
      var addin_salary_data = 'maiList[' + base_index + '].addin_salary'
      this.setData({
        [addin_salary_data]: addin_salary,
      })
    }
    if (baseType == 5) {
      punish_id = baseselectArray[index].id
      type = 1
      var chengfa_punish_name = baseselectArray[index].name
      var rwcf_id_data = 'maiList[' + base_index + '].rwcf_id'
      var rwcf_type_data = 'maiList[' + base_index + '].rwcf_type'
      this.setData({
        [rwcf_id_data]: punish_id,
        [rwcf_type_data]: chengfa_punish_name,
      })
    }

    //如果 taskend  和  addin_salary 是null时
    //接口
    // base_punish({
    //   type,
    //   token,
    //   did,
    //   sid,
    //   daycharm,
    //   taskend,
    //   addin_salary,
    //   touid,
    //   punish_id
    // }).then(re => {
    //   if (re.code == 0) {
    //     this.getmaiList();
    //   } else {
    //     console.log("接口返回数据失败", re);
    //   }
    // })
    this.dakaMailistArr()
  },
  //接口 判断惩罚方式是否可选
  cftypejiekou: function (name,cf_uid, callBack) {
    var that = this;
    let i;
    if (name.indexOf("周工资全减") != -1) {
      i = 1
    } else if (name.indexOf("日工资全减") != -1) {
      i = 2
    } else if (name.indexOf("周工资减半") != -1) {
      i = 3
    } else if (name.indexOf("日工资减半") != -1) {
      i = 4
    } else {
      i = 0
    }
    if (i && cf_uid) {
      //参数
      var token = wx.getStorageSync("userinfo").token
      var hall_id = wx.getStorageSync("hall_info").id
      var riqi = wx.getStorageSync("dangqiInfo").riqi
      cftype({
        token,
        hall_id,
        riqi,
        cf_uid,
        cf_type: i
      }, false).then(function (res) {
        if (res.code == 0) {
          if (res.check == 0) {
            callBack(null, 0);
          } else {
            callBack(null, 1);
          }
        } else {
          callBack(res);
        }
      });
    } else {
      callBack(null, 1);
    }
  },
  // 没有操作权限
  updateDakaSign() {
     
     //补卡
     if (wx.getStorageSync("update_status")){
       return 1;
     }  
     
    //超过打卡时间
    var daka_time = this.data.daka_time
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    var endtime = dangqiInfo.riqi + " " + dangqiInfo.endtime
    if (new Date().getTime() > (util.riqiTime(endtime) + Number(daka_time) * 60 * 1000)) {
      wx.showToast({
        title: '已经超过打卡时间，不能打卡',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    
  },
  //排麦列表 组成提交数据的数组
  dakaMailistArr(){
    var token = wx.getStorageSync('userinfo').token
    var did = wx.getStorageSync('dangqiInfo').id
    var manager_id = this.data.zhuchi_info.manager_id
    let dakaMailistArr = [];
    this.data.maiList.forEach((item)=>{
      if (item.uid != this.data.zhuchi_info.manager_id){
        let sid = item.id           //id
        let daycharm = item.rimeili  //日魅力是否达标 0-未达标 1-已达标
        let taskend = item.taskend   //本当任务完成情况0-未完成 1-已完成
        let addin_salary = (item.addin_salary && item.addin) ? 1 : 0  // 补档是否有工资 0-无，1-有
        let touid = item.uid   //惩罚人id
        let punish_id = 0     //默认惩罚id0 
        let type = 0          //默认 0无惩罚 1 有惩罚
        let rwcf_id = 0;       //任务惩罚id
        //惩罚措施
        if (item.taskend == 0 && item.rwcf_id) {
          rwcf_id = item.rwcf_id
          type = 1
        }
        //跳档惩罚
        if (item.tripstop == 1 && item.tdcf_id) {
          punish_id = item.tdcf_id
          type = 1
        }

        let mailistArr = {
          "token": token,
          "did": did,
          "sid": sid,
          "type": type,
          "daycharm": daycharm,
          "taskend": taskend,
          "addin_salary": addin_salary,
          "touid": touid,
          "punish_id": punish_id,
          "rwcf_id": rwcf_id
        };
        dakaMailistArr.push(mailistArr);
      }
    })
    //增加主持
    dakaMailistArr.push({ 
      "token": token,
      "did": did,
      "touid": manager_id,
      "sid": '',
      "type": '',
      "daycharm": '',
      "taskend": '',
      "addin_salary": '',
      "punish_id": '',
      "rwcf_id": ''
     });
    this.setData({
      dakaMailistArr: dakaMailistArr
    })
  },
  //打卡数据 组成提交的接口数据
  dakadatalistArr(){
     var that = this
     var token = wx.getStorageSync('userinfo').token
     var did = wx.getStorageSync('dangqiInfo').id 
     var dakadatalistArr = []
     let  typeAndshouyiren = true;
     for (var i = 0; i < this.data.get_dakadata.length; i++) {
      var userlist = this.data.get_dakadata[i].userlist
      for (var j = 0; j < userlist.length; j++) {
        let id = userlist[j]['id'] ? userlist[j]['id'] : 0
        let isedit = 0
        if (userlist[j]['isedit']){
          isedit = userlist[j]['isedit']  // 2 删除
        } else if (userlist[j]['id']){
          isedit = 1  //修改
        }else{
          isedit = 0 //新增
        }
        let type = this.data.get_dakadata[i].type
        let tid = userlist[j]['tid'] ? userlist[j]['tid']:0
        let othertid = userlist[j]['othertid'] ? userlist[j]['othertid']: 0
        let punish_id = userlist[j]['punish_id'] ? userlist[j]['punish_id']: 0
        let othertype = this.data.get_dakadata[i].id ? this.data.get_dakadata[i].id:0
        let punish_type = this.data.get_dakadata[i].id ? this.data.get_dakadata[i].id : 0
        let daguangnum = userlist[j]['daguangnum']? userlist[j]['daguangnum']:0
        let touid = 0;
        if (userlist[j]['userUid']){
          touid = userlist[j]['userUid']
        } else if (userlist[j]['touid']){
          touid = userlist[j]['touid']
        }
        let pics = userlist[j]['pics'] ? userlist[j]['pics']:''

        // 类型和用户必须同时存在
        if ((this.data.get_dakadata[i].type == 2 && daguangnum && touid) || (this.data.get_dakadata[i].type != 2 && userlist[j].name && touid) ){
          dakadatalistArr.push({
            id,
            isedit,
            token,
            did,
            type,
            tid,
            othertid,
            punish_id,
            othertype,
            punish_type,
            daguangnum,
            touid,
            pics
          })
        }else{
          typeAndshouyiren = false;
        } 
      }
     }	
   this.setData({
     dakadatalistArr
     ,typeAndshouyiren
   })
   
  },
  //提交打卡
  godaka(){
    //权限是否可以提交
    if (!wx.getStorageSync("update_status")) {
      var daka_time = this.data.daka_time
      var dangqiInfo = wx.getStorageSync('dangqiInfo')
      var endtime = dangqiInfo.riqi + " " + dangqiInfo.endtime
      if (new Date().getTime() > (util.riqiTime(endtime) + Number(daka_time) * 60 * 1000)) {
        wx.showToast({
          title: "打卡时间已过，不能打卡",
          icon: 'none'
        })
        return;
      }
    }
    //大光·福利 惩罚是否全部填写
    if(!this.data.typeAndshouyiren){
      wx.showToast({
        title: "受益人和类型不允许为空",
        icon: 'none'
      })
      return false;
    }
    //提交数据
    var token = wx.getStorageSync('userinfo').token
    var did = wx.getStorageSync('dangqiInfo').id  //档期id
    var hall_id = wx.getStorageSync('hall_info').id  //档期id
    var up_state = 0   // 0 不修改 1 打卡 1 补卡
    if(this.data.update_status){//补卡
      up_state = 1
    } else if (this.data.roles == 1){ //主持人
      up_state = 1
    }

    //小程序管理员祝助卡卡
    var xcx_bk = 0;
    if (wx.getStorageSync("update_status") && (wx.getStorageSync('dangqiInfo').manager_id != wx.getStorageSync('userinfo').uid)) {
      xcx_bk = 1;
    }
    console.log(this.data.dakaMailistArr,"福利");
    console.log(this.data.dakadatalistArr, "打卡");
    //接口
    savedakainfo({
      token:encodeURI(token),
      did,
      hall_id,
      xcx_bk,
      XDEBUG_SESSION_START:16393,
      roles:this.data.roles,
      update_state: up_state,
      task_over: this.data.zhuchi_info.task_over,
      up: encodeURI(JSON.stringify(this.data.dakaMailistArr)),
      down: encodeURI(JSON.stringify(this.data.dakadatalistArr))
    }).then(re => {
      if (re.code == 0) {
        //排麦表
         this.getmaiList(false);
        //大光福利.冠厅等等列表
         this.getdakadata(false);
        wx.showToast({
          title: "打卡成功",
          icon: 'none',
          complete:function(){
            wx.navigateBack();
          }
        })
      } else {
        console.log("保存打卡信息接口返回数据失败");
      }
    })
  },
  //判断 周工资全减，日工资全减，周工资减半，日工资减半 是否可选
  chengfashange(name, cf_uid, type, callback){

    var that = this
  
    this.cftypejiekou(name, cf_uid, function (err, res) {
      console.log("惩罚类型接口0是不允许选择1是允许", err, res);
      if (err == null) {
        if (res) {
            //判断
            var ref = 1;  
            var cd_data = ["周工资全减","日工资全减","周工资减半","日工资减半"];  
            var maiList = that.data.maiList
            maiList.forEach((item, index) => {

              let rwcf_type = '';
              if (type == "dakapaimai" && that.data.baseType == 5){ //当前操作的是任务惩罚
                 rwcf_type = ""
              }else{
                  rwcf_type = item.rwcf_type  
              }

              
              let tdcf_type = '';
              if (type == "dakapaimai" && that.data.baseType == 3) { //当前操作的是跳档惩罚
                tdcf_type = ""
              } else {
                tdcf_type = item.tdcf_type
              }
              
              if (item.uid == cf_uid && (cd_data.indexOf(rwcf_type) > -1 || cd_data.indexOf(tdcf_type) > -1)){
                      
                if (rwcf_type == "周工资全减" || tdcf_type == "周工资全减"){
                  let z_gz = ["日工资全减", "周工资减半", "日工资减半", "周工资全减"]
                  if (z_gz.indexOf(name) > -1){
                    ref = 0;
                  }
                }

                if (rwcf_type == "日工资全减" || tdcf_type == "日工资全减"){
                  if (name == "日工资减半" || name == "日工资全减"){
                    ref = 0;
                  }
                }

                if (rwcf_type == "周工资减半" || tdcf_type == "周工资减半") {
                  if (name == "日工资减半" || name == "周工资减半") {
                    ref = 0;
                  }
                }

                if (rwcf_type == "日工资减半" || tdcf_type == "日工资减半") {
                  if (name == "日工资减半") {
                    ref = 0;
                  }
                }

              }          
            });
          

        
                  //打卡受益人
                  var get_dakadata = that.data.get_dakadata
                  console.log(get_dakadata);
                  get_dakadata.forEach((item, index) => {
                    if (item["type"] == "4"){
                      item["userlist"].forEach((item_user, index_user) => {
                        var item_uid = item_user.userUid ? item_user.userUid : item_user.touid
                        var item_user_title = item_user.title ? item_user.title : ''
                        //当前操作的index_user  
                        if (type == 'fuli' && that.data.userindex == index_user){
                          item_user_title = ""
                        }

                        if (Number(item_uid) == Number(cf_uid)){ //操作的用户

                          if (item_user_title == "周工资全减") {
                            let z_gz = ["日工资全减", "周工资减半", "日工资减半", "周工资全减"]
                            if (z_gz.indexOf(name) > -1) {
                              ref = 0;
                            }
                          }

                          if (item_user_title == "日工资全减" ) {
                            if (name == "日工资减半" || name == "日工资全减") {
                              ref = 0;
                            }
                          }

                          if (item_user_title == "周工资减半" ) {
                            if (name == "日工资减半" || name == "周工资减半") {
                              ref = 0;
                            }
                          }

                          if (item_user_title == "日工资减半" ) {
                            if (name == "日工资减半") {
                              ref = 0;
                            }
                          }
                        }
                      })
                    }
                  })            
            if (!ref){
              callback(null, 0);
            }else{
              callback(null,1);
            }
        } else {
          callback(null, 0);
        }
      } else {
        callback(err);
      }
    });

  },

  //打卡结束时间  1是超过 0未超过
  outtime(){
    var daka_time = wx.getStorageSync('hall_info').daka_time;
    var endtime = wx.getStorageSync('dangqiInfo').riqi + " " + wx.getStorageSync('dangqiInfo').endtime
    //主持人在规定时间内可以打卡
    if ((new Date().getTime() > (util.riqiTime(endtime) + Number(daka_time) * 60 * 1000))) {
       return 1;
    }else{
      return 0;
    }
  },
  //修改福利 和 惩罚权限
  quanxianfuli(dakadata_info){
    
    // 补卡
    if (wx.getStorageSync("update_status")) {
        return 1
    }
   
   

    var dangqiInfo = wx.getStorageSync('dangqiInfo');
    var starttime = dangqiInfo.riqi + " " + dangqiInfo.starttime
    if (new Date().getTime() < (util.riqiTime(starttime))) {
      wx.showToast({
        title: '直播未开始',
        icon: 'none',
        duration: 2000
      })
      return 0;
    }

    //超过打卡时间
    if (this.outtime()) {
      wx.showToast({
        title: '打卡时间已结束',
        icon: 'none'
      })
      return 0;
    }

    //不是主持，也不是主播  ，是小程序管理员 
    if (this.data.roles != 1 && this.data.roles != 2) {
      wx.showToast({
        title: '没有操作权限',
        icon: 'none'
      })
      return 0;
    }

    return 1;
  },
  //角色接口
  check_roleJk(callback){
    var that =this;
    let token = wx.getStorageSync("userinfo").token
    let c_uid = wx.getStorageSync("userinfo").uid
    let dangqi_id = wx.getStorageSync("dangqiInfo").id
    let hall_id = wx.getStorageSync("hall_info").id
    check_role({
      token,
      hall_id,
      c_uid,
      dangqi_id
    }).then(function (n) {
      if(n.code == 0){
        callback(null, n)
      }else{
        callback(n);
      }
    });
  },
  //打卡删除 添加 按钮
  showdelet(){

     //直播未开始
     var starttime = this.data.dangqiInfo.riqi + " " + this.data.dangqiInfo.starttime
    let showdelet = 0;

     //主播,主持,未超过打卡时间 ,当前时间 大于  档期开始时间
    if ((this.data.roles == 2 || this.data.roles == 1) && this.outtime() == 0 && new Date().getTime() > (util.riqiTime(starttime))){
      showdelet = 1
    }

    //超过打卡时间补卡
    if (wx.getStorageSync("update_status")) {
      showdelet = 1
    }

     this.setData({
       showdelet
     })
     this.triggerEvent('showdelet', {showdelet:showdelet})
  },
  //paimai主持是否显示
  zhuchishow(){
     var show = 0;
     //主持人
     if(this.data.roles == 1){
       show = 1
     }
     //小程序管理在本档期是主播并且已过打卡时间
      if (this.data.roles == 3) {
        show = 1
      }
      //小程序管理员在本档期不是主播
      if (this.data.roles != 2 && wx.getStorageSync("userinfo").roles.indexOf("1") != -1){
        show = 1
      }   
      //补档
      if(this.data.update_status){
        show = 1
      }
      this.setData({
        zhuchidaka_isshow: show
      })
  },
  //打卡确定按钮 显示
  dakasure(){
    let dakabut = 0;
    //未超过打卡时间 主播或主持
    if ((this.data.roles == 2 || this.data.roles == 1) && this.outtime() == 0) {
      dakabut = 1
    }
    if (wx.getStorageSync("update_status") ){
      dakabut = 1
    }
    this.setData({
      dakabut: !0
    });
  },
  //图片预览
  previewimg(e){
    var src = e.currentTarget.dataset.src
    var urls = e.currentTarget.dataset.urls.split(",")
    this.setData({
      is_onshow:0
    })
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
    //获取排麦列表
    getmaiList: function (flag = true) {
        var dangqiInfo = wx.getStorageSync('dangqiInfo')
        var token = wx.getStorageSync('userinfo').token
        let hall_id = wx.getStorageSync("hall_info").id
        console.log("打卡页面");
        maiList({
          token,
          hall_id,
          dangqiid: dangqiInfo.id
        }, flag).then(re => {
          if (re.code == 0) {
    
            //正常排麦数
            var yipai_num = 0
            for (var i = 0; i < re.data.length; i++) {
              //正常排麦
              if (re.data[i].addin != 1) {
                yipai_num++
              }
              //设置日魅力 增加字段rimeiliUp 1 不能修改
              //if (re.data[i].rimeili == 1 && re.data[i].is_first_dq == 0 ){ //0不是第一个档期
              if (re.data[i].rimeili == 1 ){ 
                re.data[i].rimeiliUp = 1
              }
    
            }
    
            //跳档标记是否显示
            var time = util.riqiTime(dangqiInfo.riqi + " " + dangqiInfo.starttime)
            var tiaodangBjShow = 0;
            if (dangqiInfo.manager_id == re.myuid && new Date().getTime() > time) {
              tiaodangBjShow = 1
            }
            
            //补档按钮 1.主持人 2档期没有结束 3.可以发起补档
            var addinbtn = 0
            var endtime = util.riqiTime(dangqiInfo.riqi + " " + dangqiInfo.endtime)
            if (new Date().getTime() < endtime && re.addinbtn && re.myuid == dangqiInfo.manager_id){
              addinbtn = 1
            } 
    
            this.setData({
              kong_num: dangqiInfo.maxmic - yipai_num,
              maiList: re.data,
              maiList_copy: re.data,
              tiaodang_list: re.tiaodang_list,
              renwucf_list: re.renwucf_list,   //任务未完成时的  惩罚列表
              addinbtn: addinbtn,
              zhuchi_info: re.zhuchi_info,
              uid: re.myuid,
              addStatus: re.addinbtn,
              zc_renwucf_list: re.zc_renwucf_list, //主持人惩罚
              tiaodangBjShow
            })
            
            //记录用户打卡的信息存到数组  包括：  日魅力 本当任务  惩罚措施 跳档惩罚  补档工资
             this.dakaMailistArr()
            
          } else {
            console.log("排麦list 接口返回数据失败");
          }
        })
      },


    }
});